<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Ionize
 *
 * @package		Ionize
 * @author		Ionize Dev Team
 * @license		http://ionizecms.com/doc-license
 * @link		http://ionizecms.com
 * @since		Version 0.9.0
 */

// ------------------------------------------------------------------------

/**
 * Ionize User Controller
 * Used to login / logout an user
 *
 * @package		Ionize
 * @subpackage	Controllers
 * @category	User
 * @author		Ionize Dev Team
 *
 */

class pr_pdf extends My_Admin 
{
	
	/**
	 * Constructor
	 *
	 */
	function __construct()
	{
		parent::__construct();
		// Models model
		$this->load->model('pr_pdf_model', '', true);
		// invioces_hold model
		//$this->load->model('invoices_hold_model', '', true);
		// Locations model
		//$this->load->model('locations_model', '', true);		
		
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Default
	 *
	 */
	function index()
	{
		
		$this->output('isp_invoices_hold_tab');
	}
	
	/**
	 * New invoice hold
	 *
	 */	
	function insert()
	{	
		//get all data from tmp table
		$tmp_tables 	= $this->sibilling_model->get_by_fields('isp_invoices_tmp',array(
																						'branch_id' 	=> $this->current_user['branchs_id'],
																						'user_create' 	=> $this->current_user['username'],
																						'customer_id'	=> $this->input->post('customer_id')
																					 )
										                      );
		$grand_total	= 0;
		$i = 1;
		$error	= 0;
		if($tmp_tables>0){
				//begin transation
				$this->db->trans_begin();
					
			foreach($tmp_tables as  $tmp_table):
				// get duration from customer_sub by customer_sub_id and customer_id
				$field = array('duration','employee_id');
				$customer_sub = $this->sibilling_model->get_select_by_fields('customers_sub', array('customer_id' => $tmp_table['customer_id']),$field);
				$duration	= $customer_sub[0]['duration'];
				
				if($i == 1){
					// sum	
					$grand_total 	=  $this->sibilling_model->select_sum_field('isp_invoices_tmp','amount',array(
																												'branch_id' 	=> $this->current_user['branchs_id'],
																												'user_create' 	=> $this->current_user['username'],
																												'customer_id' 	=> $tmp_table['customer_id']
																											  )
																			);
					//count string
					$lenPrefixInvnum = strlen($this->current_user['prefix_invoice_code'])+1;
					
					if($tmp_table['invoice_type'] == 'C'){
						$get_id	= $this->sibilling_model->select_max_field('isp_invoices_hold','id_invoice',array(
																												'branch_id' => $this->current_user['branchs_id'],
																												'id_invoice'=> $this->current_user['prefix_invoice_code'].'IH'
																											  )
																	);
						
						if(count($get_id) >0){
							if(date('ym') == substr($get_id[0]['id_invoice'],$lenPrefixInvnum+1,4)){
								$inv_id		 = substr($get_id[0]['id_invoice'],-5);
								$invoice_id	 =((int)$inv_id+1);
								$invnum		 = $this->current_user['prefix_invoice_code'].'IH'.date('ym').substr('00000'.$invoice_id,-5,5);	
												
							}else
								$invnum		 = $this->current_user['prefix_invoice_code'].'IH'.date('ym').'00001';
						}else 	$invnum		 = $this->current_user['prefix_invoice_code'].'IH'.date('ym')."00001";
						
						//check grand_total include tax 10% or not
						if($this->input->post('include_tax') == 'N')
							$grand_total_amount	= $grand_total[0]['amount'];
						else
							$grand_total_amount	= $grand_total[0]['amount'] + ($grand_total[0]['amount'] * 0.1);
					}else{
						$get_id	= $this->sibilling_model->select_max_field('isp_invoices_hold','id_invoice',array(
																												'branch_id' => $this->current_user['branchs_id'],
																												'id_invoice'=> $this->current_user['prefix_invoice_code'].'NH'
																											  )
																		);
						if(count($get_id) >0){
							if(date('ym') == substr($get_id[0]['id_invoice'],$lenPrefixInvnum+1,4)){
								$inv_id		 = substr($get_id[0]['id_invoice'],-5);
								$invoice_id	 =((int)$inv_id+1);
								$invnum		 = $this->current_user['prefix_invoice_code'].'NH'.date('ym').substr('00000'.$invoice_id,-5,5);	
											
							}else
								$invnum		 = $this->current_user['prefix_invoice_code'].'NH'.date('ym').'00001';
						}else 	$invnum		 = $this->current_user['prefix_invoice_code'].'NH'.date('ym')."00001";
							
						$grand_total_amount	= $grand_total[0]['amount'];
					}
					$start_date_string	 = strtotime(date('Y-m-d'));	
					$due_date		     = date('Y-m-d', mktime(0,0,0,date('m',$start_date_string),date('d',$start_date_string) + $duration,date('Y',$start_date_string)));//end date	
					
				//trace($invnum);
					
					// insert into invoices_hold header
					$data_head = array(
									   'branch_id'		=> $tmp_table['branch_id'],
									   'id_invoice'		=> $invnum,
									   'customer_id'	=> $tmp_table['customer_id'],
									   'invoice_address'	=> $this->input->post('invoice_address'),
									   'grand_total'	=> number_format($grand_total_amount,2,'.',''),
									   'invoice_type'	=> $tmp_table['invoice_type'],
									   'logo'			=> $tmp_table['logo'],
									   'display_type'	=> $tmp_table['standard_custom'],
									   'user_create'	=> $tmp_table['user_create'],
									   'start_date'		=> $tmp_table['create_date'],
									   'due_date'		=> $due_date,
									   'create_date'	=> date('Y-m-d H:i:s'),
									   'post_status'	=> 'F',
									   'void_status'	=> 'F',
									   'bank'			=> $tmp_table['bank']
									  );
					$insert_head	= $this->sibilling_model->insert('isp_invoices_hold',$data_head);
					if(!$insert_head) $error++;
				}
				
				//check total include tax 10% or not
				if($this->input->post('include_tax') == 'N')
				{
					$sub_price		= ($tmp_table['price']*100)/110;
					$sub_total		= ($tmp_table['total']*100)/110;
					$sub_discount	= ($tmp_table['discount']*100)/110;
					$sub_amount		= ($tmp_table['amount']*100)/110;
				}
				else
				{
					$sub_price		= $tmp_table['price'];
					$sub_total		= $tmp_table['total'];
					$sub_discount	= $tmp_table['discount'];
					$sub_amount		= $tmp_table['amount'];
				}
					
				// get invoice hold ID
				$get_invoice_hold = $this->sibilling_model->get_by_field('isp_invoices_hold', 'id_invoice', $invnum);
					
				$data_sub = array(
								   'branch_id'			=> $tmp_table['branch_id'],
								   'invoice_id'			=> $get_invoice_hold[0]['id'],
								   'item_line'			=> substr('000'.$i,-3,3),
								   'customer_sub_id'	=> $tmp_table['customer_sub_id'],
								   'employee_id'		=> $customer_sub[0]['employee_id'],
								   'product_id'			=> $tmp_table['product_id'],
								   'price'				=> number_format($sub_price,2,'.',''),
								   'qty'			    => $tmp_table['qty'],
								   'total'				=> number_format($sub_total,2,'.',''),
								   'discount_type'		=> $tmp_table['discount_type'],
								   'discount'		   	=> number_format($sub_discount,2,'.',''),
								   'amount'				=> number_format($sub_amount,2,'.',''),
								   'period'				=> date('Ym'),
								   'start_date'			=> $tmp_table['create_date'],
								   'end_date'			=> $tmp_table['expire_date'],
								   'customer_status'	=> $tmp_table['customer_status']
								);
				//insert into invoices_hold_sub 
				$insert_sub	= $this->sibilling_model->insert('isp_invoices_hold_sub',$data_sub);
				
				if (!$insert_sub) $error++;
				
				// Insert to Activity Log
				$module		= 'ISP Invoices Hold/Master';
				$message	= 'Create Invoice ID: '.$invnum;
				$this->connect->saveActivityLog($module, $message, $this->current_user['username'], $data_head);	
				
				// Insert to Activity Log
				$module		= 'ISP Invoices Sub Hold/Detail';
				$message	= 'Create Invoice ID: '.$get_invoice_hold[0]['id'];
				$this->connect->saveActivityLog($module, $message, $this->current_user['username'], $data_sub);		
					
				$i++;
				
			endforeach;	
		
			if ($error == 0)
			{
				$this->db->trans_commit();
				
				//delete tmp table
				$this->sibilling_model->delete('isp_invoices_tmp',array(
																		'branch_id' 	=> $this->current_user['branchs_id'],
																		'user_create' 	=> $this->current_user['username']
																	)
										   );
				// UI update panels
				$this->update[] = array(
					'element' => 'mainPanel',
					'url' => admin_url() . 'isp_invoices_hold/page_new'
				 );					  
				// Success message
				$this->success(lang('sitech_message_new'));
			}
			else
			{
					$this->db->trans_rollback();				
					$this->error(lang('sitech_error_new'));
			}
			
		}
		else
		{
			$this->error(lang('sitech_error_new'));
		}//end if validate tmp_tables > 0
	}
	
	/**
	 * New invoice tmp 
	 *
	 */	
	function insert_tmp()
	{			
		// validate Form
		if ($this->input->post('product_id')	!= '' && 
			$this->input->post('customer_id')	!= '' &&
			$this->input->post('start_date')	!= '' &&
			$this->input->post('invoice_type')	!= '' &&
			$this->input->post('display_type')	!= '' && 
			$this->input->post('qty')			!= '' 
			)
		{

			if($this->input->post('bank') == '')
				$bank = NULL;
			else
				$bank = $this->input->post('bank');
				
			$start_date_string	    = strtotime($this->input->post('start_date')); // gernerate (day,month,year) to string
			$year					= date('Y',$start_date_string);	// get year
			$month					= date('m',$start_date_string); // get month
			$day					= date('d',$start_date_string); // get day
			$count_day_in_month 	= cal_days_in_month(CAL_GREGORIAN, $month, $year); // count day in month
			$count_day_use			= ($count_day_in_month - $day) + 1; // count day to use internet
			
			$get_price				= $this->sibilling_model->get_by_fields('isp_products',array(
																								'id' 			 => $this->input->post('product_id'),
																								'branch_id'	 =>	$this->current_user['branchs_id'],
																								'disable_status' =>	'F'
																							  )
																		);
			if($this->input->post('end_date') == '')
			{
				//not custom date
				if($this->input->post('qty') > 1)
				{
				  $end_date		        = date('Y-m-d', mktime(0,0,0,date('m',$start_date_string)+ $this->input->post('qty')-1,date('d','01'),date('Y',$start_date_string)));//end date
				  $end_date_string		= strtotime($end_date);
				  $end_month				= date('m',$end_date_string); // get end month
				  $end_year					= date('Y',$end_date_string);	// get end year
				  $count_end_day_in_month = cal_days_in_month(CAL_GREGORIAN, $end_month, $end_year); // count end day in month
				}
				else
				{
				  $end_date		        = date('Y-m-d', mktime(0,0,0,date('m',$start_date_string),date('d',$start_date_string),date('Y',$start_date_string)));//end date
				  $end_date_string		= strtotime($end_date);
				  $end_month			= date('m',$end_date_string); // get end month
				  $end_year				= date('Y',$end_date_string);	// get end year
				  $count_end_day_in_month = $count_day_in_month;
				}
				
				$end_date_in_month		= $end_year.'-'.$end_month.'-'.$count_end_day_in_month;//end date on month
				
				// set new price
				if($this->input->post('set_price'))
					$setPrice = $this->input->post('set_price');
				else
					$setPrice = $get_price[0]['price'];
					
				if($day > 1)
					$price				= ($setPrice / $count_day_in_month) * $count_day_use; // cost to use internet (count day)
				else
					$price				= $setPrice;
				
				$price_use 				= $price;
				
				if($this->input->post('qty') > 1 && $day > 1)
				{
					$qty_total_price		= $setPrice * ($this->input->post('qty')-1); // count month to use intenet and sum price  
					$total					= $price_use + $qty_total_price;
				}
				elseif($this->input->post('qty') > 1 && $day == 1)
				{
					$qty_total_price		= $setPrice * $this->input->post('qty');
					$total					= $qty_total_price;
				}
				else
					$total					= $price_use * $this->input->post('qty');
			}
			else
			{ 	
				//custom date
				$end_date_string	    = strtotime($this->input->post('end_date')); // gernerate (day,month,year) to string
				$end_year				= date('Y',$end_date_string);	// get year
				$end_month			= date('m',$end_date_string); // get month
				$end_day				= date('d',$end_date_string); // get day
				$end_date_in_month		= humanize_mdate($this->input->post('end_date'), '%Y-%m-%d');
				
				// set new price
				if($this->input->post('set_price'))
					$setPrice = $this->input->post('set_price');
				else
					$setPrice = $get_price[0]['price'];
					
				if($end_month == $month)
				{
					$count_day_custom	= $end_day - $day; //count day custom use internet
				}
				elseif($end_month > $month)
				{
					$start=strtotime(date('Y-m-d',strtotime($this->input->post('start_date'))));
					$end=strtotime(date('Y-m-d',strtotime($this->input->post('end_date'))));
					$num_day =	$end-$start;		
					$count_day_custom	= $num_day/(3600*24); //count day custom use internet
				}
				else
					$this->error(lang('sitech_error_out_of_date'));
				
				$price					= ($setPrice / $count_day_in_month) * ($count_day_custom + 1);
				$price_use				= $price;
				$total					= $price_use * $this->input->post('qty');
			}
			
			if($this->input->post('discount') > 0)
				$discount = $this->input->post('discount');
			else
				$discount = 0;
			
			if($this->input->post('discount_type') == '$')
			{
				$grand_total			= $total - $this->input->post('discount'); // discount by $
				$dis = $discount;
			}
			else
			{
				$grand_total			= $total - (($total * $this->input->post('discount'))/100); // discount by %
				$dis = ($total * $discount)/100;
			}
			
			$dis_= number_format($dis,2,'.','');
			$total_ =number_format($total,2,'.','');
			$get_price_use 	= number_format($price_use,2,'.','');
			$get_discount 	= number_format($discount,2,'.','');
			$get_total 		= number_format($total,2,'.','');

			// check discount can not biger than amount
			if($dis_ > $total_)
			{
				echo '<span style="color:#FF0000">'.lang('sitech_error_discount_biger_amount').'</span>';
			}
			else
			{	
				if($this->input->post('logo') != '')
					$logo = $this->input->post('logo');
				else
					$logo = 'Y';
				$data = array(
							  'branch_id'				=> $this->current_user['branchs_id'],
							  'customer_id'				=> strtoupper($this->input->post('customer_id')),
							  'customer_sub_id'			=> $this->input->post('customer_sub_id'),
							  'product_id'	   			=> $this->input->post('product_id'),
							  'price'					=> number_format($setPrice,2,'.',''),
							  'qty'		    			=> $this->input->post('qty'),
							  'total'					=> $get_total,
							  'discount_type'			=> $this->input->post('discount_type'),
							  'discount'				=> $get_discount,
							  'amount'					=> number_format($grand_total,2,'.',''),
							  'invoice_type'			=> $this->input->post('invoice_type'),
							  'logo'					=> $logo,
							  'standard_custom'			=> $this->input->post('display_type'),
							  'user_create'				=> $this->current_user['username'],
							  'create_date'				=> humanize_mdate($this->input->post('start_date'), '%Y-%m-%d'),
							  'expire_date'				=> $end_date_in_month,
							  'customer_status'			=> $this->input->post('status_id'),
							  'bank'					=> $bank			  							  
							);	
							
				// insert 'branch'
				$affected_rows = $this->sibilling_model->insert('isp_invoices_tmp',$data);
			}
		}
		else
		{
			echo '<h3 style="color:red;">'.lang('sitech_error_submit_form').'</h3>';
		}//endif check not null
		
		$this->page_tmp();
	}
	
	/**
	 *  void
	 *
	 */
	function void()
	{
		$id		= $this->input->post('id');
		$type	= $this->input->post('type');
		if ($id != '' && $type != '' && $this->input->post('reason'))
		{		
			//begin transation
			$this->db->trans_begin();
			$error = 0;
			$data	= array(
							'id'			=> $id,
							'void_status' 	=> 'T',
							'void_reason'	=> $this->input->post('reason'),
							'void_by_user'	=> $this->current_user['username'],
							'void_date'		=> date('Y-m-d')		
						   );
			// Update 
			$invoice_hold = $this->sibilling_model->update('isp_invoices_hold',$data);
			if(!$invoice_hold) $error++;
			
			//***
			// connection Report
			// Check Record on invoice_hold_sub_tmp	
			$wheres_check_ori	= array('invoice_id' => $id, 'note' => 'original');
			$result_check_ori	= $this->sibilling_model->get_select_by_fields('isp_invoices_hold_sub_tmp', $wheres_check_ori, 'id,product_id, customer_status, refid');
			
			$number_check_ori	= sizeof($result_check_ori);
			if($number_check_ori > 0)						
			{	
				/*	
				foreach($number_check_ori as $value)				
				{	
					if(humanize_mdate($value['create_date'],'%Y%m') == date('Ym'))
					{
						$data_insert = array(
										'branch_id'			=> $this->current_user['branchs_id'],
										'customer_id'		=> $value['customer_id'],
										'customer_sub_id'	=> $value['customer_sub_id'],
										'customer_status_id'=> $this->input->post('type'),
										'invoice_id'		=> $value['invoice_id'],
										'product_id'		=> $value['product_id'],
										'refid'				=> $value['refid'],
										'type_connection'	=> 'new',
										'period'			=> date('Ymd'),
										'reason'			=> $this->input->post('reason'),
										'create_by_user'	=> $this->current_user['username'],
										'create_date'		=> date('Y-m-d'),
										'void_status'		=> 'F',
									  );
						$insert = $this->sibilling_model->insert('connections_period',$data_insert);
						if(!$insert) $error++;
					} 
					else
					{
						$data = array(
									  'reason'			=> $this->input->post('reason'),
									  'create_by_user'	=> $this->current_user['username'],
									  'void_status'		=> 'T',
									  'void_period'		=> date('Ymd')
									  );
						$data_wheres	= array(
												'invoice_id'	=> $value['invoice_id'],
												'refid' 		=> $value['refid']
												);
									  
						$update_connection = $this->sibilling_model->update_field('connections_period',$data,$data_wheres);
						if(!$update_connection) $error++;
					} // End if(humanize_mdate($value['create_date'],'%Y%m') == date('Ym'))
				} // End foreach($number_check_ori as $value)	
				*/
				$error = 999;;
			} 
			else
			{		
				$select = "
							SELECT 		inv.customer_id,
										customer_sub_id,
										invoice_id,
										product_id,
										refid,
										create_date 
							FROM 		isp_invoices_hold_sub AS inv_sub
							LEFT JOIN 	isp_invoices_hold AS inv ON inv_sub.invoice_id = inv.id
							WHERE 		invoice_id = ".$id."
						  ";
				$results =  $this->sibilling_model->get_by_sql($select);
				
				foreach($results as $value)
				{
					if($value['refid'] > 0)
					{
						if(humanize_mdate($value['create_date'],'%Y%m') == date('Ym'))
						{	
							$data_insert = array(
												'branch_id'			=> $this->current_user['branchs_id'],
												'customer_id'		=> $value['customer_id'],
												'customer_sub_id'	=> $value['customer_sub_id'],
												'customer_status_id'=> $this->input->post('type'),
												'invoice_id'		=> $value['invoice_id'],
												'product_id'		=> $value['product_id'],
												'refid'				=> $value['refid'],
												'type_connection'	=> 'new',
												'period'			=> date('Ymd'),
												'reason'			=> $this->input->post('reason'),
												'create_by_user'	=> $this->current_user['username'],
												'create_date'		=> date('Y-m-d'),
												'void_status'		=> 'F',
											  );
							$insert = $this->sibilling_model->insert('connections_period',$data_insert);
							if(!$insert) $error++;
						}						
						else
						{
							$data = array(
										  'reason'			=> $this->input->post('reason'),
										  'create_by_user'	=> $this->current_user['username'],
										  'void_status'		=> 'T',
										  'void_period'		=> date('Ymd')
										  );
							$data_wheres	= array(
													'invoice_id'	=> $value['invoice_id'],
													'refid' 		=> $value['refid']
													);
										  
							$update_connection = $this->sibilling_model->update_field('connections_period',$data,$data_wheres);
							if(!$update_connection) $error++;
						} // End if(humanize_mdate($value['create_date'],'%Y%m') == date('Ym'))
					} // End if($value['refid'] > 0)
				} // End foreach($results as $value)
			}// End if($number_check_ori > 0)
						
			//check query error				
			if ($error > 0)
			{
				$this->db->trans_rollback();
				
				if($error >= 999)
					$this->error('Void Unsuccess, BCoz this Invoice Hold has been edited...');
				else				
					$this->error(lang('sitech_error_update'));
			}
			else
			{
				$this->db->trans_commit();
				// Insert to Activity Log
				$module		= 'ISP Invoices Hold';
				$message	= 'Void ID: '.$id;
				$this->connect->saveActivityLog($module, $message, $this->current_user['username'], $data);	
				  
				// UI update panels
				$this->update[] = array(
					'element' => 'mainPanel',
					'url' => admin_url() . 'isp_invoices_hold/'
				);				  
				 // Success message
				$this->success(lang('sitech_message_update'));
			}
		}
		else
		{
			$this->error(lang('sitech_error_submit_form'));
		}//endif check not null		
	}
	
	/**
	 * delete tmp table
	 *
	 */
	function delete($id, $customer_id)
	{
		if ($id != '')
		{
			$data = array(
							'id' 			=> $id,
							'branch_id'	 	=> $this->current_user['branchs_id'],
							'user_create'	=> $this->current_user['username']
						);
			$affected_rows = $this->sibilling_model->delete('isp_invoices_tmp',$data);
	
			if ($affected_rows > 0)
			{
				// UI update panels
				$this->update[] = array(
										'element' => 'mainPanel',
										'url' => admin_url() . 'isp_invoices_hold/page_new'
										);
			 // Success message
					$this->success(lang('sitech_message_deleted'));	
			}
			else
			{
				$this->error(lang('sitech_error_deleted'));
			}
		}
		else
		{
			$this->error(lang('sitech_error_submit_form'));
		}
	}
	
	/**
	 * Update
	 *
	 */
	function update()
	{
		$start_date_string	= strtotime($this->input->post('start_date')); // gernerate (day,month,year) to string
		$year				= date('Y',$start_date_string);	// get year
		$month				= date('m',$start_date_string); // get month
		$day				= date('d',$start_date_string); // get day
		$count_day_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year); // count day in month
		$count_day_use		= ($count_day_in_month - $day) + 1; // count day to use internet
		$get_price			= $this->sibilling_model->get_by_fields('isp_products',array(
																						'id' 		=> $this->input->post('product_id'),
																						'branch_id'	=>	$this->current_user['branchs_id']
																						)
																						);
		if($this->input->post('end_date') == '')
		{
			//not custom date
			if($this->input->post('qty') > 1)
			{
			  $end_date		        = date('Y-m-d', mktime(0,0,0,date('m',$start_date_string)+ $this->input->post('qty')-1,date('d','01'),date('Y',$start_date_string)));//end date
			  $end_date_string		= strtotime($end_date);
			  $end_month			= date('m',$end_date_string); // get end month
			  $end_year				= date('Y',$end_date_string);	// get end year
			  $count_end_day_in_month = cal_days_in_month(CAL_GREGORIAN, $end_month, $end_year); // count end day in month
			}
			else
			{
			  $end_date		        = date('Y-m-d', mktime(0,0,0,date('m',$start_date_string),date('d',$start_date_string),date('Y',$start_date_string)));//end date
			  $end_date_string		= strtotime($end_date);
			  $end_month			= date('m',$end_date_string); // get end month
			  $end_year				= date('Y',$end_date_string);	// get end year
			  $count_end_day_in_month = $count_day_in_month;
			}
			
			$end_date_in_month		= $end_year.'-'.$end_month.'-'.$count_end_day_in_month;//end date on month
			
			if($this->input->post('set_price') != '')
				$set_price = $this->input->post('set_price');
			else
				$set_price = $get_price[0]['price'];
			
			if($day > 1)
				$price				= ($set_price / $count_day_in_month) * $count_day_use; // cost to use internet (count day)
			else
				$price				= $set_price;
			
			$price_use 				= $price;

			if($this->input->post('qty') > 1 && $day > 1)
			{
				$qty_total_price		= $set_price * ($this->input->post('qty')-1); // count month to use intenet and sum price  
				$total					= $price_use + $qty_total_price;
			}
			elseif($this->input->post('qty') > 1 && $day == 1)
			{
				$qty_total_price		= $set_price * $this->input->post('qty');
				$total					= $qty_total_price;
			}
			else
				$total					= $price_use * $this->input->post('qty');
		}
		else
		{ 	
			//custom date
			$end_date_string	    = strtotime($this->input->post('end_date')); // gernerate (day,month,year) to string
			$end_year				= date('Y',$end_date_string);	// get year
			$end_month				= date('m',$end_date_string); // get month
			$end_day				= date('d',$end_date_string); // get day
			$end_date_in_month		= humanize_mdate($this->input->post('end_date'), '%Y-%m-%d');
			
			if($end_month == $month)
				$count_day_custom	= $end_day - $day; //count day custom use internet
			else
				$this->error(lang('sitech_error_out_of_date'));
			
			$price			= ($set_price / $count_day_in_month) * ($count_day_custom + 1);
			$price_use		= $price;
			$total				= $price_use * $this->input->post('qty');
		} // end if($this->input->post('end_date') == '')
		
		if($this->input->post('discount_type') == '$')
			$grand_total			= $total - $this->input->post('discount'); // discount by $
		else
			$grand_total			= $total - (($total * $this->input->post('discount'))/100); // discount by %

		if($grand_total>=0)
		{	
			if($this->input->post('discount') > 0)
				$discount = $this->input->post('discount');
			else
				$discount = 0;
			
			$error	= 0;
			
			// Get Inv_sub by id_sub
			$current_datas		= array('id' => $this->input->post('id_sub'));
			$current_inv_sub	= array_shift($this->sibilling_model->get_select_by_fields('isp_invoices_hold_sub',$current_datas, '*'));
			
			//begin transation
			$this->db->trans_begin();
			
			// Check Change (Product, Connection status) Or Not?
			if(	$current_inv_sub['product_id'] 		!= $this->input->post('product_id') || 
				$current_inv_sub['customer_status'] != $this->input->post('customer_status_id'))
			{
				if($current_inv_sub['refid'] > 0)
				{
					// Check isp_invoices_hold_sub_tmp First (Control modify alot times)
					$wheres_check		= array(
												'invoice_id'		=> $current_inv_sub['invoice_id'],
												'invoice_sub_id'	=> $current_inv_sub['id'],
												'refid'				=> $current_inv_sub['refid']
												);
					$result_check	= $this->sibilling_model->get_select_by_fields('isp_invoices_hold_sub_tmp', $wheres_check, '*', '', '');
					$number_check	= sizeof($result_check);
										
					if($number_check > 0) // Edit over 1 time
					{	
						// Check Record on invoice_hold_sub_tmp						
						$wheres_check_modify	= array('refid'	=> $current_inv_sub['refid'], 'note' => NULL);
						$result_check_modify	= $this->sibilling_model->get_select_by_fields('isp_invoices_hold_sub_tmp', $wheres_check_modify, 'id,product_id, customer_status, refid');
						$number_check_modify	= sizeof($result_check_modify);
						
						if($number_check_modify > 0)
						{
							$wheres_ori	= array('refid'	=> $current_inv_sub['refid'], 'note' => 'original');
							$result_ori	= $this->sibilling_model->get_select_by_fields('isp_invoices_hold_sub_tmp', $wheres_ori, 'id, product_id, customer_status, refid');
							$number_ori	= sizeof($result_ori);
							if($number_ori >0)
							{
								// Product and conn. are the same.
								if(	$result_ori[0]['product_id'] 		== $this->input->post('product_id') &&
									$result_ori[0]['customer_status']	== $this->input->post('customer_status_id')) 
								{																	
									// modify record
									$datas_delete	= array('refid' => $result_ori[0]['refid'], 'note' => NULL);
									$delete_sub_tmp = $this->sibilling_model->delete('isp_invoices_hold_sub_tmp', $datas_delete);
									if(!$delete_sub_tmp)
										$error++;
								}
								else
								{
									// modify product or connections
									if($result_ori[0]['product_id'] != $this->input->post('product_id')) // modify 
									{
										$datas_update	= array('customer_status' => 3);									
										$wheres_update	= array('refid' => $result_ori[0]['refid'], 'note' => NULL);
										$update_sub_tmp = $this->sibilling_model->update_field('isp_invoices_hold_sub_tmp',$datas_update, $wheres_update);
										if(!$update_sub_tmp)
											$error++;
									}
									elseif($result_ori[0]['customer_status'] != $this->input->post('customer_status_id')) 													
									{
										$datas_update	= array('customer_status' => 12);
										$wheres_update	= array('refid' => $result_ori[0]['refid'], 'note' => NULL);
										$update_sub_tmp = $this->sibilling_model->update_field('isp_invoices_hold_sub_tmp',$datas_update, $wheres_update);
										if(!$update_sub_tmp)
											$error++;
									}// End Modify Product or Connection
								}
							} // if($number_ori >0)
							
						}
						else
						{
							$wheres_ori_r	= array('refid'	=> $current_inv_sub['refid'], 'note' => 'original');
							$result_ori_r	= $this->sibilling_model->get_select_by_fields('isp_invoices_hold_sub_tmp', $wheres_ori_r, 'product_id');
							
							$data_sub_insert_tmp	= $current_inv_sub;
							$data_sub_insert_tmp['invoice_sub_id']	= $current_inv_sub['id'];
							$data_sub_insert_tmp['product_id']		= $result_ori_r[0]['product_id'];						
							unset($data_sub_insert_tmp['id']);
							unset($data_sub_insert_tmp['note']);
							
							if($current_inv_sub['product_id'] != $this->input->post('product_id'))
								$data_sub_insert_tmp['customer_status']	= 3;
							elseif($current_inv_sub['customer_status'] != $this->input->post('customer_status_id'))
								$data_sub_insert_tmp['customer_status']	= 12;
					
							$insert_sub_tmp = $this->sibilling_model->insert('isp_invoices_hold_sub_tmp',$data_sub_insert_tmp);
							if(!$insert_sub_tmp)
								$error++;
							
						}// End if($number_modify)						
					}
					else 
					{						
						// Insert 2 Records
						// - 1st Record -> All Original Record
						$datas_ori_record	= array('invoice_id' => $this->input->post('id'));
						$get_ori_record	= $this->sibilling_model->get_select_by_fields('isp_invoices_hold_sub', $datas_ori_record, '*');
						$num_ori_record	= sizeof($get_ori_record);
						for($i=0; $i<$num_ori_record; $i++)
						{
							$data_sub_insert_tmp1	= $get_ori_record[$i];
							$data_sub_insert_tmp1['invoice_sub_id']	= $get_ori_record[$i]['id'];
							$data_sub_insert_tmp1['note']	= 'original';	
							unset($data_sub_insert_tmp1['id']);
							
							$insert_sub_tmp_1 = $this->sibilling_model->insert('isp_invoices_hold_sub_tmp',$data_sub_insert_tmp1);
							if(!$insert_sub_tmp_1)
								$error++;	
						} // End for($i=0; $i<$num_ori_record; $i++)
						
						// - 2nd Record -> Modify Record
						$data_sub_insert_tmp	= $current_inv_sub;
						$data_sub_insert_tmp['invoice_sub_id']	= $current_inv_sub['id'];
						unset($data_sub_insert_tmp['id']);
						
						if($current_inv_sub['product_id'] != $this->input->post('product_id'))
							$data_sub_insert_tmp['customer_status']	= 3;
						elseif($current_inv_sub['customer_status'] != $this->input->post('customer_status_id'))
							$data_sub_insert_tmp['customer_status']	= 12;
												
						$insert_sub_tmp_2 = $this->sibilling_model->insert('isp_invoices_hold_sub_tmp',$data_sub_insert_tmp);
						if(!$insert_sub_tmp_2)
							$error++;	
							
					} // End number_check
				}
			}  // End Check Change (Product, Connection status) Or Not?

			$data_sub = array(
							  'id'				=> $this->input->post('id_sub'),
							  'product_id'	   	=> $this->input->post('product_id'),
							  'price'			=> number_format($price_use,2,'.',''),
							  'qty'		    	=> $this->input->post('qty'),
							  'total'			=> number_format($total,2,'.',''),
							  'discount_type'	=> $this->input->post('discount_type'),
							  'discount'		=> number_format($discount,2,'.',''),
							  'amount'			=> number_format($grand_total,2,'.',''),
							  'start_date'		=> humanize_mdate($this->input->post('start_date'), '%Y-%m-%d'),
							  'end_date'		=> $end_date_in_month,
							  'customer_status'	=> $this->input->post('customer_status_id')				  							  
							);
											
			// update sub
			$update_sub = $this->sibilling_model->update('isp_invoices_hold_sub',$data_sub);			
			if(!$update_sub) $error++;
			
				// get duration from customer_sub by customer_sub_id and customer_id
				$get_duration	= array_shift($this->sibilling_model->get_select_by_fields('isp_invoices_hold', array('id' => $this->input->post('id')), 'invoice_address'));
				$customer_sub	= $this->sibilling_model->get_select_by_fields('customers_sub', array('id' => $get_duration['invoice_address']), 'duration');
				$duration	= $customer_sub[0]['duration'];
				$start_date_string	 = strtotime(date('Y-m-d'));	
				$due_date		     = date('Y-m-d', mktime(0,0,0,date('m',$start_date_string),date('d',$start_date_string) + $duration,date('Y',$start_date_string)));//end date	
			
				// sum	
				$grand_total 	=  $this->sibilling_model->select_sum_field('isp_invoices_hold_sub','amount',array(
																											'branch_id' 	=> $this->current_user['branchs_id'],
																											'invoice_id' 	=> $this->input->post('id')
																										  )
																		);
				if($this->input->post('invoice_type') == 'C')
					$grand_total	= $grand_total[0]['amount'] + ($grand_total[0]['amount']*0.1);
				else
					$grand_total	= $grand_total[0]['amount'];
					
				$data_head = array(
									  'id'				=> $this->input->post('id'),
									  'grand_total'		=> number_format($grand_total,2,'.',''),
									  'invoice_type'	=> $this->input->post('invoice_type'),
									  'logo'			=> $this->input->post('logo'),
									  'display_type'	=> $this->input->post('display_type'),
									  'user_create'		=> $this->current_user['username'],
									  'create_date'		=> date('Y-m-d'),
									  'due_date'		=> $due_date,
									  'start_date'		=> humanize_mdate($this->input->post('start_date'), '%Y-%m-%d')			  							  
									);
									
				// update sub
				$update_head = $this->sibilling_model->update('isp_invoices_hold',$data_head);
				if(!$update_head) $error++;

				if($error > 0)
				{
					$this->db->trans_rollback();
					$this->error(lang('sitech_error_update'));
				}
				else
				{
	
					// Insert to Activity Log
					$module		= 'ISP Invoices Hold/ Master';
					$message	= 'Update Invoice ID: '.$this->input->post('id');
					$this->connect->saveActivityLog($module, $message, $this->current_user['username'], $data_head);	
					
					// Insert to Activity Log
					$module		= 'ISP Invoices Sub Hold/ Detail';
					$message	= 'Update Invoice ID: '.$this->input->post('id_sub');
					$this->connect->saveActivityLog($module, $message, $this->current_user['username'], $data_sub);	
					
					$this->db->trans_commit();
					// UI update panels
					$this->update[] = array(
						'element' => 'mainPanel',
						'url' => admin_url() . 'isp_invoices_hold/page_edit_list/'.$this->input->post('id')
					);
					// Success message
					$this->success(lang('sitech_message_update'));	
					
				}
									
		} 
		else
			$this->error(lang('sitech_error_discount_biger_amount'));
		// end $grand_total>0
		
		/*
		if($this->input->post('end_date') == '')
		{
			//not custom date
			if($this->input->post('qty') > 1)
			{
			  $end_date		        = date('Y-m-d', mktime(0,0,0,date('m',$start_date_string)+ $this->input->post('qty')-1,date('d','01'),date('Y',$start_date_string)));//end date
			  $end_date_string		= strtotime($end_date);
			  $end_month			= date('m',$end_date_string); // get end month
			  $end_year				= date('Y',$end_date_string);	// get end year
			  $count_end_day_in_month = cal_days_in_month(CAL_GREGORIAN, $end_month, $end_year); // count end day in month
			}
			else
			{
			  $end_date		        = date('Y-m-d', mktime(0,0,0,date('m',$start_date_string),date('d',$start_date_string),date('Y',$start_date_string)));//end date
			  $end_date_string		= strtotime($end_date);
			  $end_month			= date('m',$end_date_string); // get end month
			  $end_year				= date('Y',$end_date_string);	// get end year
			  $count_end_day_in_month = $count_day_in_month;
			}
			
			$end_date_in_month		= $end_year.'-'.$end_month.'-'.$count_end_day_in_month;//end date on month
			
			if($this->input->post('set_price') != '')
				$set_price = $this->input->post('set_price');
			else
				$set_price = $get_price[0]['price'];
			
			if($day > 1)
				$price				= ($set_price / $count_day_in_month) * $count_day_use; // cost to use internet (count day)
			else
				$price				= $set_price;
			
			$price_use 				= $price;

			if($this->input->post('qty') > 1 && $day > 1)
			{
				$qty_total_price		= $set_price * ($this->input->post('qty')-1); // count month to use intenet and sum price  
				$total					= $price_use + $qty_total_price;
			}
			elseif($this->input->post('qty') > 1 && $day == 1)
			{
				$qty_total_price		= $set_price * $this->input->post('qty');
				$total					= $qty_total_price;
			}
			else
				$total					= $price_use * $this->input->post('qty');
		}
		else
		{ 	
			//custom date
			$end_date_string	    = strtotime($this->input->post('end_date')); // gernerate (day,month,year) to string
			$end_year				= date('Y',$end_date_string);	// get year
			$end_month				= date('m',$end_date_string); // get month
			$end_day				= date('d',$end_date_string); // get day
			$end_date_in_month		= humanize_mdate($this->input->post('end_date'), '%Y-%m-%d');
			
			if($end_month == $month)
				$count_day_custom	= $end_day - $day; //count day custom use internet
			else
				$this->error(lang('sitech_error_out_of_date'));
			
			$price			= ($set_price / $count_day_in_month) * ($count_day_custom + 1);
			$price_use		= $price;
			$total				= $price_use * $this->input->post('qty');
		}
		
		if($this->input->post('discount_type') == '$')
			$grand_total			= $total - $this->input->post('discount'); // discount by $
		else
			$grand_total			= $total - (($total * $this->input->post('discount'))/100); // discount by %

		if($grand_total>=0)
		{	
			if($this->input->post('discount') > 0)
				$discount = $this->input->post('discount');
			else
				$discount = 0;
			
			$error	= 0;
			//begin transation
			$this->db->trans_begin();
			
			$data_sub = array(
									  'id'						=> $this->input->post('id_sub'),
									  'product_id'	   			=> $this->input->post('product_id'),
									  'price'					=> number_format($price_use,2),
									  'qty'		    			=> $this->input->post('qty'),
									  'total'					=> number_format($total,2),
									  'discount_type'		    => $this->input->post('discount_type'),
									  'discount'				=> number_format($discount,2),
									  'amount'					=> number_format($grand_total,2),
									  'start_date'				=> humanize_mdate($this->input->post('start_date'), '%Y-%m-%d'),
									  'end_date'				=> $end_date_in_month				  							  
									);	
											
			// update sub
			$update_sub = $this->sibilling_model->update('isp_invoices_hold_sub',$data_sub);
			if(!$update_sub) $error++;
			
				// get duration from customer_sub by customer_sub_id and customer_id
				$customer_sub		= $this->sibilling_model->get_select_by_fields('customers_sub', array('customer_id' => $this->input->post('cus_id'), 'bill_address' => 1), 'duration');
				$duration	= $customer_sub[0]['duration'];
				
				$start_date_string	 = strtotime(date('Y-m-d'));	
				$due_date		     = date('Y-m-d', mktime(0,0,0,date('m',$start_date_string),date('d',$start_date_string) + $duration,date('Y',$start_date_string)));//end date	
			
				// sum	
				$grand_total 	=  $this->sibilling_model->select_sum_field('isp_invoices_hold_sub','amount',array(
																											'branch_id' 	=> $this->current_user['branchs_id'],
																											'invoice_id' 	=> $this->input->post('id')
																										  )
																		);
				if($this->input->post('invoice_type') == 'C')
					$grand_total	= $grand_total[0]['amount'] + ($grand_total[0]['amount']*0.1);
				else
					$grand_total	= $grand_total[0]['amount'];
					
				$data_head = array(
									  'id'				=> $this->input->post('id'),
									  'grand_total'		=> number_format($grand_total,2),
									  'invoice_type'	=> $this->input->post('invoice_type'),
									  'logo'			=> $this->input->post('logo'),
									  'display_type'	=> $this->input->post('display_type'),
									  'user_create'		=> $this->current_user['username'],
									  'create_date'		=> date('Y-m-d'),
									  'due_date'		=> $due_date,
									  'start_date'		=> humanize_mdate($this->input->post('start_date'), '%Y-%m-%d')			  							  
									);
									
				// update sub
				$update_head = $this->sibilling_model->update('isp_invoices_hold',$data_head);
				if(!$update_head) $error++;
				
				if($error > 0)
				{
					$this->db->trans_rollback();
					$this->error(lang('sitech_error_update'));
				}
				else
				{
	
					// Insert to Activity Log
					$module		= 'ISP Invoices Hold/ Master';
					$message	= 'Update Invoice ID: '.$this->input->post('id');
					$this->connect->saveActivityLog($module, $message, $this->current_user['username'], $data_head);	
					
					// Insert to Activity Log
					$module		= 'ISP Invoices Sub Hold/ Detail';
					$message	= 'Update Invoice ID: '.$this->input->post('id_sub');
					$this->connect->saveActivityLog($module, $message, $this->current_user['username'], $data_sub);	
					
					$this->db->trans_commit();
					// UI update panels
					$this->update[] = array(
						'element' => 'mainPanel',
						'url' => admin_url() . 'isp_invoices_hold/page_edit_list/'.$this->input->post('id')
					);
					// Success message
					$this->success(lang('sitech_message_update'));	
					
				}
									
		} 
		else
			$this->error(lang('sitech_error_discount_biger_amount'));
		// end $grand_total>0 Last Code
		*/
	}
		
	/**
	 *  Link To Page New
	 *
	 */	
	function page_new($customer_id = false)
	{
		// get all product
		$this->template['isp_products']  = $this->sibilling_model->get_by_fields('isp_products',array(
																									'disable_status' => 'F', 
																									'price >' 		 => 0,
																									'branch_id'		 => $this->current_user['branchs_id']  
																								  )
																			  );
		// Get Customers
		$get_customers_status_id	= $this->sibilling_model->get_select_by_fields('customers_status', array('type' => array('A','P'), 'id !=' => 1), 'id');

		$customers_status_id	= NULL;
		foreach($get_customers_status_id as $key => $val):				
			$customers_status_id .= implode(',', $val).',';
		endforeach;
		$customers_status_id	= substr($customers_status_id,0,-1);

		$sql	= "
					SELECT 		*
					FROM 		customers				
					WHERE		branch_id	= {$this->current_user['branchs_id']}
						AND		customer_status_id IN	({$customers_status_id})					
					ORDER BY 	id DESC
				";
		
		$query	= $this->db->query($sql);

		if(!empty($query))
		{
			$results = array();
			if ( $query->num_rows() > 0 )
				$results = $query->result_array();
		}
		else
			$results	= array();
			
		$this->template['customers']	= $results;	

		$this->template['get_customers_status_id']	= $this->sibilling_model->get_select_by_fields('customers_status', array('type' => array('A')), 'id,name');
		
		if($customer_id != false)
			$this->template['customer_id']  = $customer_id;
		else
			$this->template['customer_id']  = NULL;
			
		
		$this->output('isp_invoices_hold_new');		
	}
	
	/**
	 *  Link To Page Edit list
	 *
	 */	
	function page_edit_list($id)
	{
		//echo '<span style="font-size:20px; color:red;">Sorry, this module is under maintenance.</span>';
		
	 	if($id != '')
		{		
			//get invoices hold
			$isp_invoices_hold  = $this->invoices_hold_model->get_join_table_to_edit_invoices(
																						  array(
																								'isp_invoices_hold.branch_id'	=> $this->current_user['branchs_id'],
																								'isp_invoices_hold.id'			=> $id,
																								'isp_invoices_hold.void_status'	=> 'F',
																								'isp_invoices_hold.post_status'	=> 'F'																				
																								)																			
																						 );
			if(sizeof($isp_invoices_hold)>0)
				 $this->template['isp_invoices_hold'] = $isp_invoices_hold;
			else 
				$this->template['isp_invoices_hold'] = array();
		}
		
		$this->output('isp_invoices_hold_edit_list');
	}
	
	/**
	 *  Link To Page void 
	 *
	 */	
	function page_void($id)
	{
		$select = "	SELECT 		inv.id,
								inv.id_invoice,
								inv_sub.refid
					FROM 		isp_invoices_hold_sub AS inv_sub
					LEFT JOIN 	isp_invoices_hold AS inv ON inv_sub.invoice_id = inv.id
					WHERE 		inv.id = ".$id."
						AND		inv.void_status = 'F'
						AND		inv.post_status = 'F'
						AND		inv.branch_id	= ".$this->current_user['branchs_id']."
					  ";
		$results =  $this->sibilling_model->get_by_sql($select);
		
		//Check Refid
		$refid	= 0;
		foreach($results as $value)
		{
			if($value['refid'] > 0)
				$refid++;
		}
		
		$this->template['count_refid']			= $refid;
		$this->template['isp_invoices_hold']	= $results;
		
		/*$this->template['isp_invoices_hold'] = $this->sibilling_model->get_by_fields('isp_invoices_hold',
																				   array(
																						  'void_status' =>'F',
																						  'post_status'	=>'F',
																						  'branch_id'	=> $this->current_user['branchs_id'],
																						  'id'			=>$id
																					    )
																				  );*/
																				  
																				  
		$this->output('isp_invoices_hold_void');
	}
	
	/**
	 *  Link To Page Edit 
	 *
	 */	
	function page_edit($id)
	{
		
		//get invoices hold
		 $this->template['isp_invoices_hold']  = $this->invoices_hold_model->get_join_table_to_edit_invoices(
																								array(
																									  'isp_invoices_hold.branch_id'		=> $this->current_user['branchs_id'],
																									  'isp_invoices_hold_sub.id'		=> $id,
																									  'isp_invoices_hold.void_status'	=> 'F',
																									  'isp_invoices_hold.post_status'	=> 'F'																				
																									  )																			
																						 );
		
		// get all product
		$this->template['isp_products']  = $this->sibilling_model->get_by_fields('isp_products',array(
																									'disable_status' => 'F', 
																									'price >' 		 => 0,
																									'branch_id'		=> $this->current_user['branchs_id']  
																								  )
																			  );
		
		$this->template['status_id']	= $this->template['isp_invoices_hold'][0]['customer_status'];
		
		// Get Connection_Status
		$wheres_status	= array('type' => 'A', 'id !=' => 1);	
		$this->template['connections_status']	= $this->sibilling_model->get_select_by_fields('customers_status', $wheres_status, 'id, name', 'type, id');
		
		$this->output('isp_invoices_hold_edit');
	}
	
	/**
	 *  Link to Page Delete
	 *
	 */	
	function page_delete($sub_id, $id)
	{	
		$this->template['sub_id']	= $sub_id;
		$this->template['id']		= $id;
		
		//get invoices hold
		$this->template['isp_invoices_hold']  = $this->invoices_hold_model->get_join_table_to_edit_invoices(
																								array(
																									  'isp_invoices_hold.branch_id'		=> $this->current_user['branchs_id'],
																									  'isp_invoices_hold_sub.id'		=> $id,
																									  'isp_invoices_hold.void_status'	=> 'F',
																									  'isp_invoices_hold.post_status'	=> 'F'																				
																									  )																			
																						 );
		// Get Connection_Status
		if($this->template['isp_invoices_hold'][0]['refid'] > 0)
			$wheres_status	= array('id' => array(2,3));
		else
			$wheres_status	= array('id' => array(13));
	
		$this->template['connections_status']	= $this->sibilling_model->get_select_by_fields('customers_status', $wheres_status, 'id, name', 'type, id');
		
		$this->output('isp_invoices_hold_delete');
		
	}
	
	/**
	 *  Link To Page tmp
	 *
	 */	
	function page_tmp()
	{
		 // get all data tmp table
		$invoices_tmp = $this->invoices_hold_model->get_join_table_show_in_tmp( array('isp_invoices_tmp','isp_products','customers','customers_sub'),
																				array(
																						'isp_invoices_tmp.branch_id' => $this->current_user['branchs_id'],
																						'isp_invoices_tmp.user_create' => $this->current_user['username']
																					  )
																	 			 );
		
		if(sizeof($invoices_tmp)>0)
		{
			 $this->template['invoice_tmp'] = $invoices_tmp;
		}
		else $this->template['invoice_tmp'] = array();
		$this->output('isp_invoices_hold_tmp');
	}
	
	/**
	 *  Link To Page active
	 *
	 */	
	function page_active($page=1)
	{	
		$nb = ($this->input->post('nb')) ? $this->input->post('nb') : '50';
		
		// Minimum
		if ($nb < 50) $nb = 50;
	
		$page = $page - 1;
		
		$offset = $page * $nb;
		
		// Like conditions
		$like = array();
		$like = array(
						'isp_invoices_hold.branch_id' 		=> $this->current_user['branchs_id'],
						'void_status'		=> 'F',
						'post_status'		=> 'F'
					 );
		foreach(array('id_invoice','id_customer','company_name') as $key)
		{
			if( $this->input->post($key))
			{				
				$like[$key] = $this->input->post($key);
			}
		}
		$date = '';
		if($this->input->post('start_date') && $this->input->post('end_date'))
			$date = "start_date BETWEEN '".humanize_mdate($this->input->post('start_date'),'%Y-%m-%d')."' AND '".humanize_mdate($this->input->post('end_date'),'%Y-%m-%d')."'";
		elseif($this->input->post('start_date'))
			$date ="start_date  = '".humanize_mdate($this->input->post('start_date'),'%Y-%m-%d')."'";
		elseif($this->input->post('end_date'))
			$date ="start_date  = '".humanize_mdate($this->input->post('end_date'),'%Y-%m-%d')."'";
		
		// Pagination
		$this->template['current_page'] = $page + 1;
		$this->template['nb'] = $nb;
		$this->template['isp_invoices_count'] = $this->sibilling_model->count_rows1('isp_invoices_hold',$like,$date);
		$this->template['isp_invoice_pages'] = ceil($this->template['isp_invoices_count'] / $nb);
		$this->template['paginations']=$this->connect->paginations($this->template['isp_invoice_pages'],$this->template['current_page']);
		
		//invoices hold head														
		$this->template['get_invoices_hold']	= $this->invoices_hold_model->get_join_table_show_in_invoices_list($like,$date,'isp_invoices_hold.id','DESC',$nb,$offset);																					
		
		if(count($this->template['get_invoices_hold']) >0){
			foreach($this->template['get_invoices_hold'] as $inv_hold)
			  {
				  //invoices hold sub
				  $this->template['get_invoices_hold_sub'][$inv_hold['id']]	= $this->invoices_hold_model->get_join_table_show_in_invoices_sub_list(
												 array(
														'isp_invoices_hold_sub.branch_id' 	=> $this->current_user['branchs_id'],
														'isp_invoices_hold_sub.invoice_id' 	=> $inv_hold['id']
														)																					 																																													                                        );
			  }
		}else $this->template['get_invoices_hold'] = array();
		
		
		
		$this->output('isp_invoices_hold_list');
	}//end function
	
	/**
	 *  Link To Page Deactive
	 *
	 */	
	function page_deactive($page=1)
	{	
		$nb = ($this->input->post('nb')) ? $this->input->post('nb') : '50';
		
		// Minimum
		if ($nb < 50) $nb = 50;
	
		$page = $page - 1;
		
		$offset = $page * $nb;
		
		// Like conditions
		$like = array();
		$like = array(
						'isp_invoices_hold.branch_id' 		=> $this->current_user['branchs_id'],
						'void_status'		=> 'T',
						'post_status'		=> 'F'
					 );
		foreach(array('id_invoice','id_customer','company_name') as $key)
		{
			if( $this->input->post($key))
			{				
				$like[$key] = $this->input->post($key);
			}
		}
		$date = '';
		if($this->input->post('start_date') && $this->input->post('end_date'))
			$date = "start_date BETWEEN '".humanize_mdate($this->input->post('start_date'),'%Y-%m-%d')."' AND '".humanize_mdate($this->input->post('end_date'),'%Y-%m-%d')."'";
		elseif($this->input->post('start_date'))
			$date ="start_date  = '".humanize_mdate($this->input->post('start_date'),'%Y-%m-%d')."'";
		elseif($this->input->post('end_date'))
			$date ="start_date  = '".humanize_mdate($this->input->post('end_date'),'%Y-%m-%d')."'";
	
		// Pagination
		$this->template['current_page'] = $page + 1;
		$this->template['nb'] = $nb;
		$this->template['isp_invoices_count'] = $this->sibilling_model->count_rows('isp_invoices_hold',$like,$date);
		$this->template['isp_invoice_pages'] = ceil($this->template['isp_invoices_count'] / $nb);
		$this->template['paginations']=$this->connect->paginations($this->template['isp_invoice_pages'],$this->template['current_page']);
		
		//invoices hold head														
		$this->template['get_invoices_hold']	= $this->invoices_hold_model->get_join_table_show_in_invoices_list($like,$date,'isp_invoices_hold.id','DESC',$nb,$offset);
		
		foreach($this->template['get_invoices_hold'] as $inv_hold)
		{
			//invoices hold sub
			$this->template['get_invoices_hold_sub'][$inv_hold['id']]	= $this->invoices_hold_model->get_join_table_show_in_invoices_sub_list(
										   array(
												  'isp_invoices_hold_sub.branch_id' 	=> $this->current_user['branchs_id'],
												  'isp_invoices_hold_sub.invoice_id' 	=> $inv_hold['id']
												  )																					 																																													                                        );
		}
		
		$this->output('isp_invoices_hold_void_list');
	}//end function
	
	
	
	/**
	 *  Release hold invoices 
	 *
	 */	
	function release()
	{
		$inv_id =	$this->input->post('invoice_id');
		if($inv_id[0] != '')
		{
			foreach($inv_id as $id)
			{
				$check_inv = $this->sibilling_model->get_by_fields('isp_invoices_hold',array('branch_id' 	=> $this->current_user['branchs_id'],
																						  'id'			=> $id,
																						  'void_status'	=> 'F'
																						 )
																);
				foreach($check_inv as $check_id)
				{
					if($check_id['post_status'] == 'R' || $check_id['post_status'] == 'P') continue;
					
					$data = array(
									'id'			  => $check_id['id'],
									'user_create'	  => $this->current_user['username'],
									'post_status'     => 'R'
								 );
					// update 
					$update = $this->sibilling_model->update('isp_invoices_hold',$data);
					
					if ($update == 0)
						$this->error(lang('sitech_error_release'));
					else
					{
						// Insert to Activity Log					
						$module		= 'ISP Invoice Hold';
						$message	= 'Release Invoice ID: '.$this->input->post('invoice_id');
						$this->connect->saveActivityLog($module, $message, $this->current_user['username'], $data);					
					}
				}
				
			}
		}// end if check data null
		$this->page_active();
	}
	
	/**
	 * View temp price 
	 *
	 */	
	function view_tmp_price()
	{
		$start_date_string	    = strtotime($this->input->post('start_date')); // gernerate (day,month,year) to string
		$year					= date('Y',$start_date_string);	// get year
		$month					= date('m',$start_date_string); // get month
		$day					= date('d',$start_date_string); // get day
		$count_day_in_month 	= cal_days_in_month(CAL_GREGORIAN, $month, $year); // count day in month
		$count_day_use			= ($count_day_in_month - $day) + 1; // count day to use internet
		
		$get_price				= $this->sibilling_model->get_by_fields('isp_products',array(
																							'id' 			 => $this->input->post('product_id'),
																							'branch_id'	 =>	$this->current_user['branchs_id'],
																							'disable_status' =>	'F'
																						  )
																	);
		if($this->input->post('end_date') == '')
		{
			//not custom date
			if($this->input->post('qty') > 1)
			{
			  $end_date		        	= date('Y-m-d', mktime(0,0,0,date('m',$start_date_string)+ $this->input->post('qty')-1,date('d','01'),date('Y',$start_date_string)));//end date
			  $end_date_string			= strtotime($end_date);
			  $end_month				= date('m',$end_date_string); // get end month
			  $end_year					= date('Y',$end_date_string);	// get end year
			  $count_end_day_in_month 	= cal_days_in_month(CAL_GREGORIAN, $end_month, $end_year); // count end day in month
			}
			else
			{
			  $end_date		        = date('Y-m-d', mktime(0,0,0,date('m',$start_date_string),date('d',$start_date_string),date('Y',$start_date_string)));//end date
			  $end_date_string		= strtotime($end_date);
			  $end_month			= date('m',$end_date_string); // get end month
			  $end_year				= date('Y',$end_date_string);	// get end year
			  $count_end_day_in_month = $count_day_in_month;
			}
			
			$end_date_in_month		= $end_year.'-'.$end_month.'-'.$count_end_day_in_month;//end date on month
			
			// set new price
			if($this->input->post('set_price'))
				$setPrice = $this->input->post('set_price');
			else
				$setPrice = $get_price[0]['price'];
				
			if($day > 1)
				$price				= ($setPrice / $count_day_in_month) * $count_day_use; // cost to use internet (count day)
			else
				$price				= $setPrice;
			
			$price_use 				= $price;
			
			if($this->input->post('qty') > 1 && $day > 1)
			{
				$qty_total_price		= $setPrice * ($this->input->post('qty')-1); // count month to use intenet and sum price  
				$total					= $price_use + $qty_total_price;
			}
			elseif($this->input->post('qty') > 1 && $day == 1)
			{
				$qty_total_price		= $setPrice * $this->input->post('qty');
				$total					= $qty_total_price;
			}
			else
				$total					= $price_use * $this->input->post('qty');
		}
		else
		{ 	
			//custom date
			$end_date_string	    = strtotime($this->input->post('end_date')); // gernerate (day,month,year) to string
			$end_year				= date('Y',$end_date_string);	// get year
			$end_month				= date('m',$end_date_string); // get month
			$end_day				= date('d',$end_date_string); // get day
			$end_date_in_month		= humanize_mdate($this->input->post('end_date'), '%Y-%m-%d');
			
			// set new price
			if($this->input->post('set_price'))
				$setPrice = $this->input->post('set_price');
			else
				$setPrice = $get_price[0]['price'];
				
			if($end_month == $month)
			{
				$count_day_custom	= $end_day - $day; //count day custom use internet
			}
			elseif($end_month > $month)
			{
				$start=strtotime(date('Y-m-d',strtotime($this->input->post('start_date'))));
				$end=strtotime(date('Y-m-d',strtotime($this->input->post('end_date'))));
				$num_day =	$end-$start;		
				$count_day_custom	= $num_day/(3600*24); //count day custom use internet
			}
			else
				$this->error(lang('sitech_error_out_of_date'));
			
			$price					= ($setPrice / $count_day_in_month) * ($count_day_custom + 1);
			$price_use				= $price;
			$total					= $price_use * $this->input->post('qty');
		}
		echo '$ '.number_format($total,2);
	}
	
	/**
	 *  Generad PDF file
	 *
	 */	
	function pdf($index= false,$bank = false) //,$display_type,$invoices_address
	{
		$this->load->library('fpdf');
		$pdf = new FPDF();	
		
		/*
		** Header
		*/	
		$data = array(
						'pd_id'		  					=> $index
					 );	
		// Get invoice head
		$invoices_head =	$this->pr_pdf_model->PDF_invoice_head();
		
		
		
		$pdf->AliasNbPages();	
		$pdf->AddPage();
		$pdf->SetAutoPageBreak(true,85);
			/*
			**	Body	
			*/ 
			$title 	= array('ID', 'PD_Name', 'Price', 'Description');
			
			$data = array(
							'pd_id'		  		=> $index
						 );	
			// Get invoices 
			$get_invoices	=	$this->pr_pdf_model->PDF_invoice_body('','pd_id','ASC');					
			trace($get_invoices);
			$pdf->body($title,$get_invoices,$invoices_head);
			
		// Generate pdf file
		$pdf->Output(FCPATH.'/files/pdf/product/product.pdf');	
		
		// Open pdf file on pop-up window
		echo '
			<script>
				window.open("'.base_url().'/files/pdf/product/product.pdf'.'","Inward PDF","width=850,height=700")
        	</script>
		';
		
	}//end function
	
	/**
	 *  Delete Product on Invoices Hold Sub by ID (Edit Invoices hold)
	 *
	 */	
	function delete_invoice_sub()
	{
		if(	$this->input->post('invoice_id') 			!= '' &&
			$this->input->post('invoice_sub_id') 		!= '' &&
			$this->input->post('customer_id') 			!= '' &&
			$this->input->post('customer_status_id')	!= '' &&
			$this->input->post('status_reason') 		!= ''
			)
		{
			$refid			= $this->input->post('refid');
			$invoice_id		= $this->input->post('invoice_id');
			$invoice_sub_hold_id	= $this->input->post('invoice_sub_id');
			
			// Check Invoices hold
			$datas_check		= array('id' => $invoice_sub_hold_id, 'invoice_id' => $invoice_id, 'branch_id' 	=> $this->current_user['branchs_id']);
			$current_inv_sub	= array_shift($this->sibilling_model->get_select_by_fields('isp_invoices_hold_sub', $datas_check, '*'));			
			if ($current_inv_sub)
			{
				// ***
				// Connection Report
				if($refid > 0)
				{
					// Check isp_invoices_hold_sub_tmp First (Control modify alot times)
					$wheres_check		= array(
												'invoice_id'		=> $current_inv_sub['invoice_id'],
												'invoice_sub_id'	=> $current_inv_sub['id'],
												'refid'				=> $current_inv_sub['refid'],
												'note'				=> 'original'
												);
					$result_check	= $this->sibilling_model->get_select_by_fields('isp_invoices_hold_sub_tmp', $wheres_check, '*', '', '');
					$number_check	= sizeof($result_check);
					
					if($number_check > 0)
					{	
						// Check isp_invoices_hold_sub_tmp First (Control modify alot times)
						$wheres_check		= array(
													'invoice_id'		=> $current_inv_sub['invoice_id'],
													'invoice_sub_id'	=> $current_inv_sub['id'],
													'refid'				=> $current_inv_sub['refid'],
													'note'				=> NULL
													);
						$check_duplicate	= $this->sibilling_model->duplicate('isp_invoices_hold_sub_tmp', $wheres_check);					
						
						$data_sub_insert_tmp	= $current_inv_sub;										
						$data_sub_insert_tmp['invoice_sub_id']	= $current_inv_sub['id'];
						$data_sub_insert_tmp['customer_status']	= $this->input->post('customer_status_id');
						unset($data_sub_insert_tmp['id']);
						
						if(!$check_duplicate)
						{	
							$insert_sub_tmp = $this->sibilling_model->insert('isp_invoices_hold_sub_tmp',$data_sub_insert_tmp);
							if(!$insert_sub_tmp)
								$error++;
						}
						else
						{
							$insert_sub_tmp = $this->sibilling_model->update_field('isp_invoices_hold_sub_tmp',$data_sub_insert_tmp, $wheres_check);
							if(!$insert_sub_tmp)
								$error++;
						}
						// End check_duplicate
					}
					else
					{
						// Insert 2 Records
						// - 1st Record -> All Original Record
						$datas_ori_record	= array('invoice_id' => $this->input->post('invoice_id'));
						$get_ori_record	= $this->sibilling_model->get_select_by_fields('isp_invoices_hold_sub', $datas_ori_record, '*');
						$num_ori_record	= sizeof($get_ori_record);
						for($i=0; $i<$num_ori_record; $i++)
						{
							$data_sub_insert_tmp1	= $get_ori_record[$i];
							$data_sub_insert_tmp1['invoice_sub_id']	= $get_ori_record[$i]['id'];
							$data_sub_insert_tmp1['note']	= 'original';	
							unset($data_sub_insert_tmp1['id']);
							  
							$insert_sub_tmp_1 = $this->sibilling_model->insert('isp_invoices_hold_sub_tmp',$data_sub_insert_tmp1);
							if(!$insert_sub_tmp_1)
								$error++;	
						} // End for($i=0; $i<$num_ori_record; $i++)
						
						// - 2nd Record -> Modify Record
						$data_sub_insert_tmp	= $current_inv_sub;
						$data_sub_insert_tmp['invoice_sub_id']	= $current_inv_sub['id'];
						$data_sub_insert_tmp['customer_status']	= $this->input->post('customer_status_id');
						unset($data_sub_insert_tmp['id']);
												
						$insert_sub_tmp_2 = $this->sibilling_model->insert('isp_invoices_hold_sub_tmp',$data_sub_insert_tmp);
						if(!$insert_sub_tmp_2)
							$error++;	
					}
				}
				// End ^
				// ***
		
				$affected_rows = $this->sibilling_model->delete('isp_invoices_hold_sub', $datas_check);
		
				if ($affected_rows > 0)
				{
					// Insert to Activity Log
					$module		= 'ISP Invoices Hold';
					$message	= 'Update ID: '.$invoice_id.' And Delete Sub ID: '.$invoice_sub_hold_id;
					$this->connect->saveActivityLog($module, $message, $this->current_user['username'], $datas_check);
	
					/*echo '<script type="text/javascript">ION.alert(Lang.get("sitech_message_deleted"));</script>';*/
					
					// UI update panels
					$this->update[] = array(
						'element' => 'mainPanel',
						'url' => admin_url() . 'isp_invoices_hold/page_edit_list/'.$invoice_id
					 );	
					 // Success message
					$this->success(lang('sitech_message_deleted'));
				}
				
			}
			else
				$this->success(lang('sitech_error_deleted'));
				/*echo '<script type="text/javascript">ION.alert(Lang.get("sitech_error_deleted"));</script>';*/
		} 
		else
			$this->error(lang('sitech_error_submit_form'));
	}
		
}//end class

/* End of file isp_products.php */
/* Location: ./application/controllers/admin/isp_products.php */